package com.cloud.code.算法.队列.循环队列;

import com.cloud.code.算法.队列.Queue;

public class LoopQueue<E> implements Queue<E> {

    private E[] data;

    private int size;

    private int front, tail;


    public LoopQueue(int initcapacity) {
        data = (E[]) new Object[initcapacity+1];
        size = 0;
        front = 0;
        tail = 0;

    }

    public LoopQueue() {
        this(10);
    }

    public int getCapacity() {
        return data.length - 1;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public void push(E e) {
        if ((tail + 1) % data.length == front)
            resize(getCapacity() * 2);

        data[tail] = e;
        tail = (tail + 1) % data.length;
        size++;
    }

    private void resize(int capaticy) {
        System.out.println("触发扩容，旧的容量："+getCapacity());
        E[] newData = (E[]) new Object[capaticy + 1];

        for (int i = 0; i < size; i++) {
            newData[i] = data[i + front % data.length];
        }
        data = newData;
        front = 0;
        tail = size;
        System.out.println("触发扩容，新的容量："+getCapacity());

    }

    @Override
    public E pop() {

        if (isEmpty())
            throw new IllegalArgumentException("Queue is empty");
        E ret = data[front];
        data[front] = null;
        front = (front + 1) % data.length;
        size--;
        return ret;
    }

    @Override
    public boolean isEmpty() {
        return tail == front;
    }


}
